<template>
  <div class="add-card">
    <header class="add-header">
      <el-page-header :content="title" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">车辆信息</div>
        <div class="form">
          <el-form ref="carInfoForm" :model="carInfoForm" :rules="carInfoRules" label-width="100px">
            <el-form-item label="车主姓名" prop="personName">
              <label v-if="check">{{ carInfoForm.personName }}</label>
              <el-input v-else v-model="carInfoForm.personName" :disabled="disabled" />
            </el-form-item>
            <el-form-item label="联系方式" prop="phoneNumber">
              <label v-if="check">{{ carInfoForm.phoneNumber }}</label>
              <el-input v-else v-model="carInfoForm.phoneNumber" :disabled="disabled" />
            </el-form-item>
            <el-form-item label="车辆号码" prop="carNumber">
              <label v-if="check">{{ carInfoForm.carNumber }}</label>
              <el-input v-else v-model="carInfoForm.carNumber" :disabled="disabled" />
            </el-form-item>
            <el-form-item label="车辆品牌" prop="carBrand">
              <label v-if="check">{{ carInfoForm.carBrand }}</label>
              <el-input v-else v-model="carInfoForm.carBrand" :disabled="disabled" />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="form-container">
        <div class="title">最新一次月卡缴费信息</div>
        <div class="form">
          <!--
            v-model 绑定日期选择的值
            当type为date 时候就一个值，为daterange 就为2个值
            value-format:绑定的格式
            type:日期组件类型
              date：单独日期
              daterange：2个日期范围
              range-separator分隔符
          -->
          <el-form v-if="(type != 'check')" ref="feeForm" :model="feeForm" :rules="feeFormRules" label-width="100px">
            <el-form-item label="有效日期" prop="payTime">
              <el-date-picker
                v-model="feeForm.payTime"
                :disabled-date="disabledDate()"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            <el-form-item label="支付金额" prop="paymentAmount">
              <el-input v-model="feeForm.paymentAmount" />
            </el-form-item>
            <el-form-item label="支付方式" prop="paymentMethod">
              <el-select v-model="feeForm.paymentMethod" clearable>
                <el-option
                  v-for="item in payMethodList"
                  :key="item.id"
                  :value="item.id"
                  :label="item.name"
                />
              </el-select>
            </el-form-item>
          </el-form>
          <!-- 查看月卡功能 -->
          <el-table v-else :data="renowList" style="width: 100%">
            <el-table-column label="序号" type="index" :index="indexMethod" width="150" />
            <el-table-column prop="cardDate" label="日期" width="480" />
            <el-table-column prop="paymentMethod" label="支付金额" width="280" />
            <el-table-column prop="paymentAmount" label="支付方式" width="280" />
            <el-table-column prop="createTime" label="办理时间" width="180" />
            <el-table-column prop="createUser" label="办理人" />
          </el-table>
        </div>
      </div>
    </main>
    <footer v-if="!check" class="add-footer">
      <div class="btn-container">
        <el-button @click="resetFn">重置</el-button>
        <el-button type="primary" @click="rulsForm">确定</el-button>
      </div>
    </footer>
  </div>
</template>

<script>
import { validCarName, validCarNumber, validMobile } from '@/utils/validate.js'
import { addCardAPI, getCardDetailAPI, updatCardAPI, userCardAPI, renowCardAPI } from '@/apis/card'
export default {
  data() {
    return {
      // 车辆信息表
      carInfoForm: {
        personName: '', // 车主姓名
        phoneNumber: '',
        carNumber: '',
        carBrand: ''
      },
      // 校验车辆信息
      carInfoRules: {
        personName: [
          {
            required: true,
            message: '请输入车主姓名',
            tirgger: 'blur'
          },
          { validator: this.validCarNameFn, trigger: 'blur' }
        ],
        phoneNumber: [
          { required: true, message: '请输入联系方式', trigger: 'blur' },
          { validator: this.validPhoneNumberFn, trigger: 'blur' }
        ],
        carNumber: [
          { required: true, message: '请输入车牌号', trigger: 'blur' },
          { validator: this.validCarNumberFn, trigger: 'blur' }
        ],
        carBrand: [
          { required: true, message: '请输入车辆品牌', trigger: 'blur' }
        ]
      },
      // 缴费信息表单
      feeForm: {
        payTime: [], // 支付时间
        paymentAmount: null, // 支付金额
        paymentMethod: null // 支付方式
      },
      // 缴费规则
      feeFormRules: {
        payTime: [
          {
            required: true,
            message: '请选择支付时间'
          }
        ],
        paymentAmount: [
          {
            required: true,
            message: '请输入支付金额',
            trigger: 'blur'
          }
        ],
        paymentMethod: [
          {
            required: true,
            message: '请选择支付方式',
            trigger: 'change'
          }
        ]
      },
      // 支付方式列表
      payMethodList: [
        {
          id: 'Alipay',
          name: '支付宝'
        },
        {
          id: 'WeChat',
          name: '微信'
        },
        {
          id: 'Cash',
          name: '线下'
        }
      ],
      // 查看用户缴费信息
      renowList: [],
      indexMethod: 1
    }
  },
  computed: {
    id() {
      return this.$route.query.id
    },
    type() {
      return this.$route.query.type
    },
    title() {
      if (this.type === 'edit') {
        return '编辑月卡'
      } else if (this.type === 'check') {
        return '查询月卡'
      } else if (this.type === 'renow') {
        return '月卡续费'
      } else {
        return '新增月卡'
      }
    },
    // 续费状态
    disabled() {
      if (this.type === 'renow') {
        return true
      } else {
        return false
      }
    },
    // 查看状态
    check() {
      if (this.type === 'check') {
        return true
      } else {
        return false
      }
    }
  },
  created() {
    console.log('查询参数:', this.$route.query)
    if (this.id) {
      this.getCardDetail(this.id)
    }
    if (this.type === 'check') {
      // console.log(11);
      this.getUserCardList(this.id)
      this.renowFn()
    }
  },
  mounted() {
    // this.carInfoForm = {
    //   personName: '托尼',
    //   phoneNumber: '13300000000',
    //   carNumber: '粤B123456',
    //   carBrand: '比亚迪'
    // }
    // this.feeForm = {
    //   payTime: ['2024-10-24', '2025-11-23'],
    //   paymentAmount: 2,
    //   paymentMethod: 'Wechat'
    // }
  },
  methods: {
    validPhoneNumberFn(rule, value, callback) {
      if (validMobile(value)) callback()
      else callback(new Error('请输入正确的格式的手机号码'))
    },
    validCarNumberFn(rule, value, callback) {
      if (validCarNumber(value)) callback()
      else callback(new Error('请输入正确车牌号'))
    },
    validCarNameFn(rule, value, callback) {
      if (validCarName(value)) callback()
      else callback(new Error('请输入正确的中文姓名'))
    },
    async rulsForm() {
      if (this.disabled) {
        // console.log('dianle')
        await this.$refs.feeForm.validate()

        const obj = {
          ...this.feeForm
        }
        obj.cardStartDate = this.feeForm.payTime[0]
        obj.cardEndDate = this.feeForm.payTime[1]
        obj.rechargeId = +new Date() + Math.floor(Math.random() * (100 + 1))
        delete obj.payTime
        // 路由获取的id
        obj.carInfoId = this.id
        const res = await renowCardAPI(obj)
        console.log(res)
      } else {
        await this.$refs.carInfoForm.validate()
        await this.$refs.feeForm.validate()

        const obj = {
          ...this.carInfoForm,
          ...this.feeForm
        }

        obj.cardStartDate = this.feeForm.payTime[0]
        obj.cardEndDate = this.feeForm.payTime[1]
        delete obj.payTime
        if (this.id) {
          await updatCardAPI(obj)
        } else {
          await addCardAPI(obj)
        }
      }
      this.$message({
        message: '当前车辆信息更新到服务器',
        type: 'success'
      })
      this.$router.back()
    },
    resetFn() {
      if (!this.type === 'renow') {
        this.$refs.feeForm.resetFields()
        this.$refs.carInfoForm.resetFields()
      }
    },
    async getCardDetail(id) {
      const res = await getCardDetailAPI(id)
      // console.log(res)
      for (const key in this.carInfoForm) {
        this.carInfoForm[key] = res.data[key]
      }
      if (this.type === 'edit') {
        for (const key in this.feeForm) {
          if (key === 'payTime') {
            const { cardStartDate, cardEndDate } = res.data
            this.feeForm.payTime = [cardStartDate, cardEndDate]
          } else {
            this.feeForm[key] = res.data[key]
          }
        }
      }
      // 进到这里就是编辑车辆信息
      this.carInfoForm.carInfoId = this.id
      this.feeForm.rechargeId = res.data.rechargeId
    },
    disabledDate() {
      return true
    },
    // 回显当前日期
    getStartDate() {
      const now = new Date()
      const y = now.getFullYear()
      const m = now.getMonth() + 1
      const d = now.getDate() + 1
      return `${y}-${m}-${d}`
    },
    // 如果是续费页面
    renowFn() {
      const start = this.getStartDate()
      // this.feeForm.payTime =[]
      this.feeForm.payTime = [start, '']
    },
    // 获取用户缴费记录信息
    async getUserCardList(id) {
      const res = await userCardAPI(id)
      // console.log(res)
      // for(const key in this.renowList){
      //   console.log( res.data.rechargeList[key])
      // }
      // const {rechargeList} =  res.data.rechargeList
      this.renowList = res.data.rechargeList
      // console.log(typeof rechargeList)
      for (let i = 0; i < res.data.rechargeList.length; i++) {
        this.renowList[i].cardDate = res.data.rechargeList[i].cardStartDate + ' 至 ' + res.data.rechargeList[i].cardEndDate
      }
    }

  }
}
</script>

  <style scoped lang="scss">
.add-card {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }
      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
    .preview {
      img {
        width: 100px;
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>
